package com.scalar.chiptrack.operations.finishedGoods.actionCommands;

import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.finishedGoods.FinishedGoodsHelper;
import com.scalar.chiptrack.operations.finishedGoods.EquivalentPartNumber;
import com.scalar.chiptrack.operations.finishedGoods.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.finishedGoods.forms.FinishedGoodsEntryForm;
import com.scalar.chiptrack.operations.process.dao.VendorLocationDAO;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * User: Murali Krishna Yengala
 * Date: May 31, 2005
 * Time: 12:34:07 PM
 */
public class FinishedGoodsUpdateCommand extends ChipTrackExtendedAction{
        public ActionForward executeRequest( ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response) throws Exception
        {

            HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
            HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );
            HttpSession session = request.getSession();

            if( !(isTokenValid( request)) )
            {
                errors.put("Finished Goods is already saved", null);
                FinishedGoodsHelper.setBaseProductsAndCustomers( request, errors);
                request.setAttribute ( SessionKeys.ERROR_MESSAGES , errors );
                return  mapping.findForward("new");
            }
            FinishedGoodsEntryForm finishedGoodsEntryForm = ( FinishedGoodsEntryForm ) form;
            int baseProductId = finishedGoodsEntryForm.getBaseProductIdI();
            int customerId = finishedGoodsEntryForm.getCustomerIdI();
            

            String[] fgiProcessStepIds = finishedGoodsEntryForm.getFgiProcessStepIds();
            String[] customerIds = finishedGoodsEntryForm.getCustomerIds();

            String partNumber = finishedGoodsEntryForm.getFinishedGoodsPartNo() == null ? "" : finishedGoodsEntryForm.getFinishedGoodsPartNo().trim();
            ArrayList processParameters = finishedGoodsEntryForm.getParametersList();
            ArrayList selectedVendorLocations = FinishedGoodsHelper.getVendorLocations( request, true);

            DBTransaction dbTransaction = null;
            boolean success = false;

            try
            {
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();
                // Check for partnumber in Product map table

                int processStepId =finishedGoodsEntryForm.getProcessStepIdI();
                FinishedGoodsDAO.updateProcessStepTable( dbTransaction, processStepId, finishedGoodsEntryForm.getDescription());
                FinishedGoodsDAO.updateProductTable(dbTransaction, processStepId, finishedGoodsEntryForm );
                FinishedGoodsDAO.deleteFromFgToFgiMapTable(dbTransaction, processStepId);
                FinishedGoodsDAO.saveFgToFgiMappings( dbTransaction, processStepId, fgiProcessStepIds, baseProductId);
                FinishedGoodsDAO.deleteCustomersForFG( dbTransaction, processStepId );
                FinishedGoodsDAO.saveCustomersForFG( dbTransaction, processStepId, customerIds );

                ArrayList dupPartNos = finishedGoodsEntryForm.getEquivalentPartNosList();
                if( dupPartNos != null)
                {
                    Iterator dupPartsIterator = dupPartNos.iterator();
                    while( dupPartsIterator.hasNext() )
                    {
                        EquivalentPartNumber dupPartNumber = ( EquivalentPartNumber) dupPartsIterator.next();
                        if( dupPartNumber.isDelete() )
                        {
                            dupPartsIterator.remove();
                        }
                    }
                }
                FinishedGoodsDAO.saveProductMap(dbTransaction, processStepId, dupPartNos, selectedVendorLocations );
                FinishedGoodsDAO.saveParameters( dbTransaction, processStepId, processParameters);
                VendorLocationDAO.deleteVendorLocations ( dbTransaction , processStepId );
                if ( ( selectedVendorLocations != null ) && ( selectedVendorLocations.size () > 0 ) )
                {
                    VendorLocationDAO.saveVendorLocations ( dbTransaction , processStepId , selectedVendorLocations.iterator () );
                }
                success = true;
            }
            catch ( ScalarException se )
            {
                success = false;
                se.printStackTrace ();
                errors.put( ERROR_INTERNAL_SERVER_ERROR, "");
            }
            catch ( Exception se )
            {
                success = false;
                se.printStackTrace ();
                errors.put( ERROR_INTERNAL_SERVER_ERROR, "");
            }
            finally
            {
                // Rollback or Commit the Transaction
                if ( success == true )
                {
                    if ( dbTransaction != null )
                    {
                        dbTransaction.commit ();
                    }
                    session.removeAttribute("finishedGoodsEntryForm");
                    resetToken( request);
                    info.put ( "Finished Goods = "+partNumber,"Updated Successfully" );
                }
                else
                {
                errors.put ( "Finished Goods = "+partNumber, "Could not Update Finished Goods" );
                    dbTransaction.rollback ();
                }
            }
            FinishedGoodsHelper.setBaseProductsAndCustomers( request, errors);
            request.setAttribute ( SessionKeys.ERROR_MESSAGES , errors );
            request.setAttribute ( SessionKeys.INFO_MESSAGES , info );

            FinishedGoodsHelper.setBaseProductsAndCustomers( request, errors);
            request.setAttribute("fgiProductsList", new ArrayList());
            return mapping.findForward("finishedGoodsSearch");
        }
}
